package article

import (
	"context"
	"gitee.com/chicken-c/go-learn/webook/internal/repostiory"
	"gitee.com/chicken-c/go-learn/webook/pkg/logger"
	"gitee.com/chicken-c/go-learn/webook/pkg/saramsx"
	"github.com/IBM/sarama"
	"time"
)

type InteractiveReadEventConsumer struct {
	repo   repostiory.InterActiveRepository
	client sarama.Client
	l      logger.Logger
}

func NewInteractiveReadEventConsumer(repo repostiory.InterActiveRepository, client sarama.Client, l logger.Logger) *InteractiveReadEventConsumer {
	return &InteractiveReadEventConsumer{repo: repo, client: client, l: l}
}

// 批量消费
func (i *InteractiveReadEventConsumer) Start() error {
	cg, err := sarama.NewConsumerGroupFromClient("interactive", i.client)
	if err != nil {
		return nil
	}
	go func() {
		er := cg.Consume(context.Background(), []string{TopicReadEvent}, saramsx.NewBatchHandler(i.l, i.Consume))
		if er != nil {
			i.l.Error("退出消费", logger.Field{
				Key: "error",
				Val: er,
			})
		}
	}()

	return err
}

// 单个进行消费
func (i *InteractiveReadEventConsumer) StartV1() error {
	cg, err := sarama.NewConsumerGroupFromClient("interactive", i.client)
	if err != nil {
		return nil
	}
	go func() {
		er := cg.Consume(context.Background(), []string{TopicReadEvent}, saramsx.NewHandler(i.l, i.ConsumeV1))
		if er != nil {
			i.l.Error("退出消费", logger.Field{
				Key: "error",
				Val: er,
			})
		}
	}()

	return err
}

func (i *InteractiveReadEventConsumer) Consume(msg []*sarama.ConsumerMessage, event []ReadEvent) error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	bizs := make([]string, 0, len(event))
	bizIds := make([]int64, 0, len(event))
	for i := 0; i < len(event); i++ {
		bizs = append(bizs, "article")
		bizIds = append(bizIds, event[i].Aid)
	}
	return i.repo.BatchIncrReadCnt(ctx, bizs, bizIds)
}

func (i *InteractiveReadEventConsumer) ConsumeV1(msg *sarama.ConsumerMessage, event ReadEvent) error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	return i.repo.IncrReadCnt(ctx, "article", event.Aid)
}
